import React, { useEffect, useMemo, useRef, useState } from 'react';
import styles from './index.module.scss';
import { HotQuestion, useOrchestrationStore } from '@/store/orchestrationStore';
import orchestrationService from '@/api/services/orchestrationService';
import { hotIssues } from '@/common';
import { AppType } from '@/common/app/constants';
import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useInitializeData } from '@/store/configStore';
import { VariableInputEnum } from '@/types/workflow/constant';
import { fetchConfigStatus } from '@/utils/common';
import { message } from 'antd';
import FunasrRecorder from '../chat/components/FunasrRecorder';
import MessageSendInputHome from '../homepage/components/MessageSendInputHome';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { useUserInfo } from '@/store/userStore';
import { ChatBoxVariableInput } from '@/components/chat-box/VariableInputItem';
import { getTimePeriod } from '@/utils/time';
import HotQuestions from './components/HotQuestions';
import HomeMenuList from '@/pages/components/menus/HomeMenuList';
import FusionAppList from './components/FusionAppList';
import { useParams } from '@/router/hooks';
import AppImageDisplay from '../homepage/components/AppImageDisplay';
import DigitalHuman from '@/components/digital-human';
import { useMetahumanStore } from '@/store/metahumanStore';

interface HomepageProps {
  onChatStart?: (message: string) => void;
  workflowDebug?: boolean;
  widthFlag?: boolean; //处理融合应用和智能体的宽度问题
}

const Homepage2: React.FC = ({ onChatStart, workflowDebug = false, widthFlag }: HomepageProps) => {
  const { VITE_LICENSE_FLAG: LICENSEFLAG } = import.meta.env;
  const licenseFlag = LICENSEFLAG === 'true' ? true : false;
  const initializeData = useInitializeData();
  const [isLicenseModalOpen, setIsLicenseModalOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);


  const { username } = useUserInfo();

  const { sceneImage, appLogo, setFusionAppId } = useOrchestrationStore();
  const [isLoading, setIsLoading] = useState(false);

  const { virtualAvatarEnabled, permissionConfig } = useMetahumanStore();

  const handleActivateClick = () => {
    setIsLicenseModalOpen(true);
  };

  const handleLicenseCancel = () => {
    setIsLicenseModalOpen(false);
  };

  const {
    workflow,
    configurations,
    hotQuestions,
    userSelectVariables,
    subAppDetail,
    isInOrchestrationPage,
    appDetail,
    appName,
  } = useOrchestrationStore();

  const isWebRTCSopport = useMemo(() => {
    return typeof window !== 'undefined' && typeof window.RTCPeerConnection !== 'undefined';
  }, []);

  const isMetahumanEnabled = useMemo(() => {
    return virtualAvatarEnabled && permissionConfig?.metahumanQuota && isWebRTCSopport;
  }, [virtualAvatarEnabled, permissionConfig, isWebRTCSopport]);

  // wokflow
  // const { appDetail } = useContextSelector(AppContext, (v) => v);
  const [chatStart, setChatStart] = useState(false);

  const userInputVariables = useMemo(() => {
    if (subAppDetail?.variables || subAppDetail?.workflow?.chatConfig?.variables) {
      const subAppVariables =
        subAppDetail?.variables?.length > 0
          ? subAppDetail?.variables
          : subAppDetail?.workflow?.chatConfig?.variables;
      const subAppVariablesFliter = subAppVariables?.filter(
        (item: any) => item?.type !== VariableInputEnum.custom,
      );
      return subAppVariablesFliter || userSelectVariables;
    }
    return (
      workflow?.chatConfig?.variables?.filter((item) => item.type !== VariableInputEnum.custom) ||
      userSelectVariables
    );
  }, [workflow, userSelectVariables, subAppDetail]);

  useEffect(() => {
    console.log('userInputVariables', userInputVariables);
  }, [userInputVariables]);

  useEffect(() => {
    console.log('aaa', appDetail?.fusionApp);
  }, [appDetail]);
  useEffect(() => {
    console.log('aaa', appDetail?.fusionApp);
  }, [appDetail]);

  const chatStarted =
    chatStart || userInputVariables?.length === 0 || userInputVariables?.length === undefined;

  // const isHotIssuesOpen = useMemo(() => fetchConfigStatus(configurations, 'hot_issues'), [configurations]);

  useEffect(() => {
    console.log(
      'chatStarted',
      chatStarted,
      chatStart,
      userInputVariables?.length === 0,
      userInputVariables?.length === undefined,
    );
  }, [chatStarted, chatStart, userInputVariables]);

  const isHotIssuesOpen = useMemo(() => {
    const isEnable = fetchConfigStatus(configurations, 'hot_issues');
    const isSubEnable = fetchConfigStatus(subAppDetail?.configurations, 'hot_issues');
    return subAppDetail ? isSubEnable : isEnable;
  }, [configurations, subAppDetail]);

  const startFlowChat = (value: boolean) => {
    setChatStart(value);
    // if (value) {
    //   onChatStart && onChatStart(undefined);
    // }
  };
  // workflow end

  const isConfigAvailable = configurations.length != 0;

  const sceneImageConfig =
    (configurations.find((config) => config.name === 'scene_image')?.default_value as string) ||
    sceneImage;

  const openingRemarks = workflow
    ? workflow.chatConfig.welcomeText
    : (configurations.find((config) => config.name === 'opening_remarks')
      ?.default_value as string) || '';

  const { isPc } = useWindowWidth();

  // 修改类型定义，使用联合类型来支持两种不同的对象结构
  const [hotTitle, setHotTitle] = useState<(hotIssues | HotQuestion | { content: string })[]>([
    // { content: '我可以报考哪些专业' },
    // { content: '我需要准备哪些材料' },
    // { content: '如何申请奖学金' }
  ]);

  const handleSend = () => { };
  const changeInputType = () => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    setVoice(!voice);
  };
  const handleInterrupt = () => { };
  const onSTT = (status: number) => {
    if (status == 0) {
      setIsMessageSend(true);
    }
    if (status == 1) {
      setIsMessageSend(true);
    }
    if (status == 2) {
      setIsMessageSend(false);
    }
  };
  const onVoiceStop = (inputValue: string) => {
    if (licenseFlag && !initializeData?.is_license_valid) {
      handleActivateClick();
      return;
    }
    if (inputValue && onChatStart) {
      onChatStart(inputValue);
    }
  };
  const onInterrupt = () => {
    setIsMessageSend(false);
  };
  const [voice, setVoice] = useState(false);

  const [isMessageSend, setIsMessageSend] = useState(false);

  useEffect(() => {
    // fetchAppInfo();

    setTimeout(() => {
      !isPc && checkTextOverflow();
    }, 500);
  }, []);

  const { appId = '' } = useParams() as { appId: string };

  const fetchAppInfo = async () => {
    if (subAppDetail?.app_id) {
      const responseSubApp = await orchestrationService.getAppHotIssue(subAppDetail?.app_id);
      setHotTitle(responseSubApp?.hot_issues?.map((item) => ({ content: item.content })) || []);
      setIsLoading(true);
      return;
    }
    if (!appId) {
      // message.error('未获取到应用ID');
      setHotTitle([]);
      setIsLoading(true);
      return;
    }
    if (hotQuestions && hotQuestions.length > 0) {
      setHotTitle(hotQuestions.map((item) => ({ content: item.content })));
    } else {
      const responseApp = await orchestrationService.getAppHotIssue(appId);
      setHotTitle(responseApp?.hot_issues?.map((item) => ({ content: item.content })) || []);
    }
    setIsLoading(true);
  };

  useEffect(() => {
    console.log('appId', appId);
    fetchAppInfo();
  }, [appId, configurations, subAppDetail, hotQuestions]);

  const messageGreeting = document.querySelector('.greeting-message');
  const messageGreetingHeight = useMemo(() => {
    return messageGreeting?.clientHeight;
  }, [messageGreeting?.clientHeight]);

  const checkTextOverflow = () => {
    const scrollTextElements = document.querySelectorAll('.scrolltext');
    console.log(scrollTextElements);

    scrollTextElements.forEach((element) => {
      const spanElement = element.querySelector('span');
      if (!spanElement) return;

      const elementWidth = element.clientWidth || 0;
      const spanWidth = spanElement.clientWidth || 0;

      console.log(spanWidth, elementWidth, spanWidth / elementWidth);

      if (spanWidth > elementWidth) {
        const translateXValue = `${(1 - spanWidth / elementWidth) * 100}%`;
        console.log(translateXValue);

        // 如果文本超出容器，则添加动画类
        spanElement.classList.add('animate');
        spanElement.style.setProperty('--translateXValue', translateXValue);
      } else {
        // 如果文本没有超出容器，则移除动画类
        spanElement.classList.remove('animate');
      }
    });
  };

  const { voiceEnabled } = useOrchestrationStore();

  useEffect(() => {
    if (!voiceEnabled && voice) {
      setVoice(false);
    }
  }, [voiceEnabled]);

  return (
    <div
      className={isPc ? styles['homepage2-container'] : ''}
      style={
        widthFlag
          ? {
            height: '100%',
            width: '100%',
          }
          : { height: '100%' }
      }
    >
      {/* 子应用logo列表 */}
      {location?.pathname?.includes('fusion') && isPc && (
        <FusionAppList
          // apps={appDetail?.fusionApp}
          className="mt-6"
        />
      )}
      {isPc && (
        <>
          <div className={`${styles['gradient-left']}`} />
        </>
      )}
      {isPc && (
        <>
          <div className={`${styles['gradient-right']}`} />
        </>
      )}

      {/* {!isPc && (
        <>
          <div className="pointer-events-none absolute left-0 top-0 z-0">
            <SvgIcon icon="mobile-chat-bg-left" size={375} />
          </div>
          <div className="pointer-events-none absolute -top-14 right-0 z-0">
            <SvgIcon icon="mobile-chat-bg-right" size={375} />
          </div>
        </>
      )} */}
      <div className="relative z-1000 flex h-full items-center justify-center">
        <div
          ref={containerRef}
          className={`flex h-full flex-col items-center ${isPc ? 'w-[80%] justify-end mb-[50vh]' : 'w-full justify-start'}`}
          style={{
            // marginBottom: isPc ? '50vh' : undefined,
            // marginBottom: containerRef.current ? `${containerRef.current.offsetHeight / 2}px` : '50vh',
          }}
        >
          <div
            className="flex w-full flex-row items-start justify-between"
            style={{ maxWidth: '800px' }}
          >
            {!isPc && isMetahumanEnabled && (
              <div className="fixed left-1/2 top-0 z-1000 flex w-full -translate-x-1/2 transform justify-center">
                <div className="relative">
                  <div className="relative">
                    <DigitalHuman/>
                    {/* 渐变遮罩层，底部渐变到白色 */}
                    <div
                      className="pointer-events-none absolute bottom-0 left-0 h-1/2 w-full"
                      style={{
                        background: 'linear-gradient(to bottom, rgba(255,255,255,0) 0%, #fff 30%)',
                      }}
                    />
                  </div>
                </div>
              </div>
            )}
            {!isPc && (
              <div
                className={`z-20 flex h-full flex-col items-center  gap-2 self-center [-ms-overflow-style:none] [scrollbar-width:none] ${isHotIssuesOpen || workflow?.chatConfig.hotQuestionConfig?.open ? '' : ''
                  }`}
                style={{
                  width: isPc ? '80%' : '100%',
                  maxWidth: '800px',
                  margin: 'auto',
                  // paddingBottom: isPc ? '100px' : '50px',
                  // paddingTop:
                  //   isHotIssuesOpen || workflow?.chatConfig.hotQuestionConfig?.open
                  //     ? isPc
                  //       ? 'unset'
                  //       : '30px'
                  //     : '40%',
                  marginTop: '200px',
                  height: 'calc(100vh - 320px)',
                  overflow: 'auto',
                  paddingTop: '10px',
                  backgroundColor: 'white',
                  borderRadius: '24px',
                }}
              >
                {(isConfigAvailable || workflow) && (
                  <AvatarDisplay src={appLogo} size={56} className="h-[56px] w-[56px]" />
                )}
                <div className="w-full text-center text-base">
                  👋 {getTimePeriod()}{username ? `，${username}` : ''}!
                </div>
                <div className="px-5 text-center text-[24px] font-font-weight-600 text-text-5 outline-none">
                  {appName ? `我是${appName}` : ''}
                </div>
                <div className="w-full whitespace-normal break-words px-5 text-center text-[14px] font-font-weight-400 text-text-3 outline-none">
                  {openingRemarks || ''}
                </div>
                <HotQuestions
                  hotTitle={hotTitle}
                  isShow={Boolean(isHotIssuesOpen || workflow?.chatConfig.hotQuestionConfig?.open)}
                  isPc={isPc}
                  licenseFlag={licenseFlag}
                  isLicenseValid={Boolean(initializeData?.is_license_valid)}
                  handleActivateClick={handleActivateClick}
                  onChatStart={(msg) => {
                    console.log('msg', msg);
                    onChatStart && onChatStart(msg);
                  }}
                  chatStarted={chatStarted}
                />
              </div>
            )}

            {isPc && (
              <div
                className={`flex h-full flex-row items-end justify-center ${virtualAvatarEnabled ? 'w-[500px]' : 'w-full'
                  }`}
              >
                {isPc && (
                  <div
                    className="mr-4 flex flex-shrink-0 flex-col items-start justify-start"
                    style={{ height: virtualAvatarEnabled ? messageGreetingHeight + 'px' : '100%' }}
                  >
                    <AvatarDisplay
                      src={appLogo || 'default'}
                      size={50}
                      className="h-[50px] w-[50px] flex-shrink-0"
                    />
                  </div>
                )}

                {isPc && (
                  <div className="greeting-message flex-1 pb-4">
                    <div className="mb-2 w-full text-left text-base">
                      👋 {getTimePeriod()}，{username}!
                    </div>
                    {appName && <div className="mb-2 w-full text-left text-3xl font-bold">我是{appName}</div>}
                    <div className="text-left text-[#4E5969]">{openingRemarks}</div>
                    <div className="py-2">
                      <HotQuestions
                        hotTitle={hotTitle}
                        isShow={Boolean(
                          isHotIssuesOpen || workflow?.chatConfig.hotQuestionConfig?.open,
                        )}
                        isPc={isPc}
                        licenseFlag={licenseFlag}
                        isLicenseValid={Boolean(initializeData?.is_license_valid)}
                        handleActivateClick={handleActivateClick}
                        onChatStart={(msg) => {
                          console.log('msg', msg);
                          onChatStart && onChatStart(msg);
                        }}
                        chatStarted={chatStarted}
                      />
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* 右侧固定区域 */}
            {isPc && isMetahumanEnabled && (
              <div className="h-[400px]flex-shrink-0 flex w-[300px] items-end">
                <div className="text-sm text-gray-600">
                  <DigitalHuman/>
                </div>
              </div>
            )}
          </div>

          <div
            className={`relative z-20 flex w-full rounded-[12px]`}
            style={{
              maxWidth: '800px',
            }}
          >
            {isPc && (
              <MessageSendInputHome
                handleSend={handleSend}
                changeInputType={changeInputType}
                handleInterrupt={handleInterrupt}
                isMessageSend={isMessageSend}
                isHome={true}
                voice={voice}
                onInterrupt={onInterrupt}
                onVoiceStop={onVoiceStop}
                onSTT={onSTT}
                onChatStart={(msg) => {
                  onChatStart && onChatStart(msg);
                }}
                setHomepageChatStart={setChatStart}
              ></MessageSendInputHome>
            )}
            {!isPc && (
              <div
                className={`fixed bottom-0 left-0 right-0 flex w-full flex-col items-center justify-center p-2`}
              >
                <div className="relative flex w-full items-center rounded-xl bg-white">
                  <MessageSendInputHome
                    handleSend={handleSend}
                    changeInputType={changeInputType}
                    handleInterrupt={handleInterrupt}
                    isMessageSend={isMessageSend}
                    isHome={true}
                    voice={voice}
                    onInterrupt={onInterrupt}
                    onVoiceStop={onVoiceStop}
                    onSTT={onSTT}
                    onChatStart={(msg) => {
                      onChatStart && onChatStart(msg);
                    }}
                    setHomepageChatStart={setChatStart}
                  ></MessageSendInputHome>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Homepage2;
